<template>
  <el-row>
    <div class="block">
      <el-date-picker v-model="value2" type="datetimerange" :shortcuts="shortcuts" range-separator="To" start-placeholder="起始日期" end-placeholder="结束日期" />
    </div>
    <div class="block">
      <el-select v-model="value3" placeholder="选择区域" style="width: 240px">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </div>

  </el-row>
  <div>
    <el-card><div ref="chart" style="height: 300px; width: 1300px"></div></el-card>
    <el-card><div ref="chart2" style="height: 300px; width: 1300px"></div></el-card>
    <el-card>
      <el-table :data="pagedTableData" border style="width: 100%" @sort-change="handleSortChange">
        <el-table-column prop="start_time" label="开始时间" width="200" :formatter="formatTime.formatTime" sortable />
        <el-table-column prop="end_time" label="结束时间" width="200" :formatter="formatTime.formatTime" />
        <el-table-column prop="during_time" label="停机时长" width="180" :sort-method="sortDuringTime" sortable/>
        <el-table-column prop="sub_area" label="区域" width="180" />
        <el-table-column prop="equipment_id" label="工位号" width="180" />
        <el-table-column prop="shift" label="班次" width="180" />
        <el-table-column prop="call_type" label="类型" width="180" />
        <el-table-column fixed="right" label="操作" width="100">
      <template #default="{ row }">
        <el-button size="small" type="text" @click="handleDelete(row)">删除</el-button>
      </template>
    </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalItems"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, toRef, toRefs, computed } from "vue";
import * as echarts from "echarts"; //引入echarts核心模块
import axios from "axios"; //引入echarts核心模块
import { useRouter } from "vue-router";
import ElementPlus from 'element-plus';


const value2 = ref([]);

const shortcuts = [
  {
    text: "近1周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 7);
      return [start, end];
    },
  },
  {
    text: "近2周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 14);
      return [start, end];
    },
  },
  {
    text: "近1月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      return [start, end];
    },
  },
];
const chart = ref(); 
const chart2 = ref();
const chartInstance2 = ref(null);
const series_data2 = ref();
const series_data = ref();
const series_data1 = ref();
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(0);

const formatTime = computed(() => ({
  formatTime(row, column) {
    if (column.property === 'start_time' || column.property === 'end_time') {
      return row[column.property].split('.')[0];
    }
    return row[column.property];
  }
}));

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  updatePagedData();
};
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  updatePagedData();
};

const pagedTableData = ref([]);
const sortDuringTime = (a, b) => a.during_time - b.during_time;

const handleSortChange = ({ column, prop, order }) => {
  if (prop === 'during_time') {
    if (order === 'ascending') {
      tableData.value.sort(sortDuringTime);
    } else if (order === 'descending') {
      tableData.value.sort((a, b) => sortDuringTime(b, a));
    } else {
    }
    updatePagedData();
  }
};
const updatePagedData = () => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  pagedTableData.value = tableData.value.slice(startIndex, endIndex);
};
const handleDelete = async (row) => {
  tableData.value = tableData.value.filter(item => item !== row);

  updateChartData(row);
  updatePagedData();
};

const updateChartData = (deletedRow) => {
  const updatedTimeSumBySubArea = new Map(series_data1.value.map((subArea, index) => [subArea, series_data.value[index]]));
  updatedTimeSumBySubArea.set(deletedRow.sub_area, 
    updatedTimeSumBySubArea.get(deletedRow.sub_area) - deletedRow.during_time / 60);
  series_data1.value = Array.from(updatedTimeSumBySubArea.keys());
  series_data.value = Array.from(updatedTimeSumBySubArea.values()).map(val => parseFloat(val.toFixed(2)));

  const updatedTimeSumByEquipmentId = new Map(series_data4.value.map((sum, index) => [series_data3.value[index], sum]));
  const updatedFaultCountByEquipmentId = new Map(series_data5.value.map((count, index) => [series_data3.value[index], count]));

  if (updatedTimeSumByEquipmentId.has(deletedRow.equipment_id)) {
    updatedTimeSumByEquipmentId.set(deletedRow.equipment_id, 
      updatedTimeSumByEquipmentId.get(deletedRow.equipment_id) - deletedRow.during_time / 60);
    updatedFaultCountByEquipmentId.set(deletedRow.equipment_id, 
      updatedFaultCountByEquipmentId.get(deletedRow.equipment_id) - 1);
  }

  resortData(updatedTimeSumByEquipmentId, updatedFaultCountByEquipmentId);

  initChart();
  initChart2();
};

const resortData = (timeSumByEquipmentId, faultCountByEquipmentId) => {
  const sortedEntries = Array.from(timeSumByEquipmentId.entries()).sort((a, b) => b[1] - a[1]);

  const sortedFaultCountByEquipmentId = new Map();
  sortedEntries.forEach(([equipmentId, _]) => {
    sortedFaultCountByEquipmentId.set(equipmentId, faultCountByEquipmentId.get(equipmentId));
  });

  series_data3.value = sortedEntries.map(entry => entry[0]);
  series_data4.value = sortedEntries.map(entry => parseFloat(entry[1].toFixed(2)));
  series_data5.value = Array.from(sortedFaultCountByEquipmentId.values());
};
const initChart = async () => {
  if (chart.value == null) {
    return;
  }

  echarts.dispose(chart.value);
  var myChart = echarts.init(chart.value);
  myChart.setOption({});
  let option = {
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        var result = "";
        for (var i = 0; i < params.length; i++) {
          var param = params[i];
          if (i === 0) {
            result += param.name + "<br/>";
          }
          result += param.seriesName + ": " + param.value + "<br/>";
        }
        return result;
      },
    },
    legend: {
      data: ["停机时长"],
      orient: "horizontal", // 改为水平显示
      left: "left", // 将图例放置在左侧
      top: "top", // 将图例放置在顶部
      itemGap: 10, // 图例项之间的间距
    },
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ["line", "bar"] },
        restore: { show: true },
        saveAsImage: { show: true },
      },
    },

    title: {
      text: "各区域下线停线损失",
      left: "center",
      subtext: "分钟",
      textStyle: {
        color: "black", 
      },
      subtextStyle: {
        fontWeight: "bold",
      },
    },
    xAxis: {
      type: "category",
      data: series_data1.value,
    },
    yAxis: {
      type: "value",
      splitLine: { 
      show: false,
    },
    },
    series: [
      {
        name: "停机时长",
        data: series_data.value,
        type: "bar",
        color: "#edafda",
        label: {
        show: true, 
        position: 'top', 
        formatter: '{c} 分钟', 
        color: 'black', 
      }
      },
    ],
  };

  myChart.setOption(option);
};

const initChart2 = async () => {
  if (chartInstance2.value == null) {
    return;
  }

  echarts.dispose(chartInstance2.value);
  var myChart2 = echarts.init(chartInstance2.value);
  myChart2.setOption({});

  let option2 = {
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        var result = "";
        for (var i = 0; i < params.length; i++) {
          var param = params[i];
          if (i === 0) {
            result += param.name + "<br/>";
          }
          result += param.seriesName + ": " + param.value + "<br/>";
        }
        return result;
      },
    },
    legend: {
      data: ["停机次数", "停机时长"],
      orient: "horizontal", 
      left: "left", 
      top: "top", 
      itemGap: 10, 
    },
    title: {
      text: `${value3.value} 设备停机时间总计`,
      left: "center",
      textStyle: {
        color: "black", 
      },
      subtextStyle: {
        fontWeight: "bold",
      },
    },
    xAxis: {
      type: "category",
      data: series_data3.value,
    },
    dataZoom: [
      {
        type: "slider", 
        start: 0, 
        end: 100, 
      },
      {
        type: "inside", 
        start: 90, 
        end: 100, 
      },
    ],
    yAxis: [
      {
        type: "value",
        name: "停机时长 (分钟)",
        axisLabel: {
          formatter: "{value} 分钟",
        },
        splitLine: { 
        show: false,
    },
      },
      {
        type: "value",
        name: "停机次数",
        axisLabel: {
          formatter: "{value}",
        },
        position: "right",
        offset: 20,
        splitLine: { 
        show: false,
    },
      },
    ],
    series: [
      {
        name: "停机时长",
        data: series_data4.value,
        type: "bar",
        color: "#5470c6",
        yAxisIndex: 0,
        itemStyle: {
          normal: {
            cursor: 'pointer',
            barBorderRadius: 5,
            borderColor: '#ccc',
            borderWidth: 1
          }
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
      },
      {
        name: "停机次数",
        data: series_data5.value,
        type: "line",
        color: "#edafda",
        yAxisIndex: 1
      },
    ],
  };
  myChart2.on('click', (params) => {
    console.log('Clicked:', params);
    const equipmentId = params.name; 
    useShowDataInHtmlForTable(equipmentId);
  });
  myChart2.setOption(option2);
};

onMounted(() => {
  const oneWeekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  const today = new Date();
  value2.value = [oneWeekAgo, today];
  use_show_data_in_html2();
  use_show_data_in_html3();
  chartInstance2.value = chart2.value; 
  initChart2();
  updatePagedData();
});

const value3 = ref("装配A");
const router = useRouter();
const options = [
  { value: "装配A", label: "装配A" },
  { value: "装配B", label: "装配B" },
  { value: "装配C", label: "装配C" },
  { value: "缸体M1", label: "缸体M1" },
  { value: "缸体M2", label: "缸体M2" },
  { value: "缸盖M1", label: "缸盖M1" },
  { value: "缸盖M2", label: "缸盖M2" },
  { value: "曲轴M1", label: "曲轴M1" },
];
const excludedpoint = ["1006", "1265","1115","1315","1245","1195","1405","1200","1235","1140","1165","1126","1196","1355","1055","1035","2155","2476","2115","2185","2356","2120","2055","2006","2145","2515","2355","2225","3105","3062"];
function formatDate(d: string) {
  var date = new Date(d);
  var YY = date.getFullYear() + "-";
  var MM = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var hh = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var mm = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
  var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return YY + MM + DD + " " + hh + mm + ss;
}

var construct_url = "";
var construct_url2 = "";
watch([toRef(value2), toRef(value3)], ([newDateRange, newValue3]) => {
  const start_time = formatDate(newDateRange[0]);
  const end_time = formatDate(newDateRange[1]);
  construct_url = "http://10.64.35.32:8000/man_ana_sql_server/get_MachineFaultHistory/?" + "start_time=" + start_time?.toString() + "&end_time=" + end_time?.toString() + "&page_size=" + 100001;
  construct_url2 = "http://10.64.35.32:8000/man_ana_sql_server/get_MachineFaultHistory/?" + "start_time=" + start_time?.toString() + "&end_time=" + end_time?.toString() + "&sub_area=" + newValue3 + "&page_size=" + 100001;
  use_show_data_in_html2();
  use_show_data_in_html3();
});

const series_data3 = ref();
const series_data4 = ref();
const series_data5 = ref();

const use_show_data_in_html2 = async () => {
  console.log(construct_url);
  const response = await axios.get(construct_url);
  const data = response.data.filter(item => 
    !excludedpoint.includes(item.equipment_id) &&
    ['1430', '2490', '3120', '230', '190', '150B'].includes(item.equipment_id) && 
    (item.equipment_id !== '190' || (item.sub_area === '缸盖M1' || item.sub_area === '缸盖M2')) &&
    (item.equipment_id !== '150B' || (item.sub_area === '曲轴M1')) 
  );
  console.log(data);

  series_data1.value = [];
  series_data.value = [];
  series_data2.value = [];

  const timeSumBySubAreaAndEquipment = new Map();

  data.forEach(item => {
    const key = `${item.sub_area}_${item.equipment_id}`;
    const duringTime = item.during_time;

    if (!timeSumBySubAreaAndEquipment.has(key)) {
      timeSumBySubAreaAndEquipment.set(key, 0);
    }
    if (duringTime > 15 && duringTime <= 3600) {
      timeSumBySubAreaAndEquipment.set(
        key,
        parseFloat((timeSumBySubAreaAndEquipment.get(key) + duringTime / 60).toFixed(2))
      );
    }
  });

  const sortedEntries = Array.from(timeSumBySubAreaAndEquipment.entries()).sort((a, b) => b[1] - a[1]);

  sortedEntries.forEach(([key, value]) => {
    series_data1.value.push(key); 
    series_data.value.push(parseFloat(value.toFixed(2))); 
  });

  console.log(series_data1.value, series_data.value);
  initChart();
};

const use_show_data_in_html3 = async () => {
  console.log(construct_url2);
  const response = await axios.get(construct_url2);
  const data = response.data.filter(item => !excludedpoint.includes(item.equipment_id));
  console.log(data);

  series_data3.value = [];
  series_data4.value = [];
  series_data5.value = [];

  const timeSumByEquipmentId = new Map();
  const faultCountByEquipmentId = new Map();

  data.forEach(item => {
    const equipmentId = item.equipment_id;
    const duringTime = item.during_time;

    if (!timeSumByEquipmentId.has(equipmentId)) {
      timeSumByEquipmentId.set(equipmentId, 0);
    }

    if (duringTime > 15 && duringTime <= 3600) {
      timeSumByEquipmentId.set(
        equipmentId,
        parseFloat((timeSumByEquipmentId.get(equipmentId) + duringTime / 60).toFixed(2))
      );

      if (!faultCountByEquipmentId.has(equipmentId)) {
        faultCountByEquipmentId.set(equipmentId, 0);
      }
      faultCountByEquipmentId.set(equipmentId, faultCountByEquipmentId.get(equipmentId) + 1);
    }
  });

  const sortedEntries = Array.from(timeSumByEquipmentId.entries()).sort((a, b) => b[1] - a[1]);

  const sortedFaultCountByEquipmentId = new Map();
  sortedEntries.forEach(([equipmentId, _]) => {
    sortedFaultCountByEquipmentId.set(equipmentId, faultCountByEquipmentId.get(equipmentId));
  });

  series_data3.value = sortedEntries.map(entry => entry[0]); 
  series_data4.value = sortedEntries.map(entry => parseFloat(entry[1].toFixed(2))); 
  series_data5.value = Array.from(sortedFaultCountByEquipmentId.values()); 

  initChart2();
};
const useShowDataInHtmlForTable = async (equipmentId) => {
  try {
    const start_time = formatDate(value2.value[0]);
    const end_time = formatDate(value2.value[1]);

    const url = "http://10.64.35.32:8000/man_ana_sql_server/get_MachineFaultHistory/?" +
                "start_time=" + start_time.toString() +
                "&end_time=" + end_time.toString() +
                "&sub_area=" + value3.value +
                "&equipment_id=" + equipmentId +
                "&page_size=10001";

    console.log(url);
    const response = await axios.get(url);
    const data = response.data.filter(item => !excludedpoint.includes(item.equipment_id));
    tableData.value = data.filter(item => item.during_time > 15 && item.during_time < 3600);
    totalItems.value = tableData.value.length;
    updatePagedData();
    console.log(data);
  } catch (error) {
    console.error(error);
    ElMessage.error('加载数据失败。');
  }
};
</script>

<style scoped>
h3 {
  color: black;
}

.block {
  padding: 20px;
  text-align: center;
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.el-select .el-scrollbar__wrap {
  max-height: 50px !important;
  overflow-y: auto !important;
}
</style>
